//
//  GameViewController.m
//  shandong_porker
//
//  Created by 陈文洁 on 2025/8/8.
//  Updated for MVVM architecture on 2025-01-08.
//

#import "GameViewController.h"
#import "Views/Scenes/SPGameScene.h"
#import "Models/Game/SPGameManager.h"
#import "Core/Categories/UIColor+Theme.h"

@interface GameViewController ()

@property (nonatomic, strong) UIButton *pauseButton;
@property (nonatomic, strong) UIButton *menuButton;
@property (nonatomic, strong) SPGameManager *gameManager;

@end

@implementation GameViewController

#pragma mark - Lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建游戏管理器
    [self setupGameManager];
    
    // 设置SpriteKit视图
    [self setupSKView];
    
    // 创建游戏场景
    [self setupGameScene];
    
    // 设置UI控件
    [self setupUIControls];
    
    // 不自动开始游戏，等待用户点击"开始游戏"按钮
    NSLog(@"GameViewController: 游戏界面已加载，等待用户开始游戏");
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // 隐藏导航栏
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

#pragma mark - Setup Methods

- (void)setupGameManager {
    // 创建玩家名称数组
    NSArray<NSString *> *playerNames = @[@"玩家", @"AI-1", @"AI-2", @"AI-3", @"AI-4"];
    
    // 创建游戏管理器
    self.gameManager = [[SPGameManager alloc] initWithPlayerNames:playerNames 
                                                     aiDifficulty:SPAIDifficultyMedium 
                                                       smallBlind:50 
                                                         bigBlind:100];
}

- (void)setupSKView {
    self.skView = [[SKView alloc] initWithFrame:self.view.bounds];
    self.skView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.skView.backgroundColor = [UIColor sp_backgroundDarkColor];
    
    // SpriteKit调试选项（仅在Debug模式下显示）
#ifdef DEBUG
    self.skView.showsFPS = YES;
    self.skView.showsNodeCount = YES;
#endif
    
    [self.view addSubview:self.skView];
}

- (void)setupGameScene {
    // 创建游戏场景
    CGSize sceneSize = self.skView.bounds.size;
    self.gameScene = [[SPGameScene alloc] initWithSize:sceneSize gameManager:self.gameManager];
    self.gameScene.scaleMode = SKSceneScaleModeAspectFill;
    
    // 呈现场景
    [self.skView presentScene:self.gameScene];
}

- (void)setupUIControls {
    // 暂停按钮
    self.pauseButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.pauseButton setTitle:@"⏸️" forState:UIControlStateNormal];
    self.pauseButton.titleLabel.font = [UIFont systemFontOfSize:24];
    self.pauseButton.tintColor = [UIColor sp_chipGoldColor];
    self.pauseButton.frame = CGRectMake(20, 50, 44, 44);
    [self.pauseButton addTarget:self action:@selector(pauseButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.pauseButton];
    
    // 菜单按钮
    self.menuButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.menuButton setTitle:@"☰" forState:UIControlStateNormal];
    self.menuButton.titleLabel.font = [UIFont systemFontOfSize:24];
    self.menuButton.tintColor = [UIColor sp_chipGoldColor];
    self.menuButton.frame = CGRectMake(self.view.bounds.size.width - 64, 50, 44, 44);
    self.menuButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    [self.menuButton addTarget:self action:@selector(menuButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.menuButton];
}

#pragma mark - Game Control

- (void)startNewGame {
    NSLog(@"开始新游戏");
    [self.gameManager startNewGame];
}

- (void)pauseGame {
    [self.gameManager pauseGame];
    [self.gameScene pauseScene];
    [self.pauseButton setTitle:@"▶️" forState:UIControlStateNormal];
}

- (void)resumeGame {
    [self.gameManager resumeGame];
    [self.gameScene resumeScene];
    [self.pauseButton setTitle:@"⏸️" forState:UIControlStateNormal];
}

#pragma mark - Button Actions

- (void)pauseButtonTapped:(UIButton *)sender {
    if (self.gameManager.isPaused) {
        [self resumeGame];
    } else {
        [self pauseGame];
    }
}

- (void)menuButtonTapped:(UIButton *)sender {
    NSLog(@"菜单按钮被点击");
    
    // 创建操作菜单
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"游戏菜单" 
                                                                             message:nil 
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
    
    // 新游戏选项
    UIAlertAction *newGameAction = [UIAlertAction actionWithTitle:@"新游戏" 
                                                            style:UIAlertActionStyleDefault 
                                                          handler:^(UIAlertAction * _Nonnull action) {
        [self startNewGame];
    }];
    [alertController addAction:newGameAction];
    
    // 设置选项
    UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:@"设置" 
                                                             style:UIAlertActionStyleDefault 
                                                           handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"打开设置");
    }];
    [alertController addAction:settingsAction];
    
    // 退出选项
    UIAlertAction *quitAction = [UIAlertAction actionWithTitle:@"退出游戏" 
                                                         style:UIAlertActionStyleDestructive 
                                                       handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alertController addAction:quitAction];
    
    // 取消选项
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" 
                                                           style:UIAlertActionStyleCancel 
                                                         handler:nil];
    [alertController addAction:cancelAction];
    
    // iPad适配
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        alertController.popoverPresentationController.sourceView = sender;
        alertController.popoverPresentationController.sourceRect = sender.bounds;
    }
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - Touch Handling

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self.skView];
    
    // 将触摸位置转换为场景坐标
    CGPoint sceneLocation = [self.skView convertPoint:location toScene:self.gameScene];
    
    // 检查是否点击了扑克桌
    SKNode *touchedNode = [self.gameScene nodeAtPoint:sceneLocation];
    if ([touchedNode.name isEqualToString:@"pokerTable"]) {
        NSLog(@"点击了扑克桌");
    }
}

#pragma mark - Orientation

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return UIInterfaceOrientationMaskPortrait; // 改为竖屏模式
    } else {
        return UIInterfaceOrientationMaskAll;
    }
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

// 注意：shouldAutorotate 在 iOS 13+ 中已废弃，使用 supportedInterfaceOrientations 来控制旋转
// - (BOOL)shouldAutorotate {
//     return YES;
// }

#pragma mark - Memory Management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // 处理内存警告
}

- (void)dealloc {
    // 清理资源
    [self.gameManager endGame];
}

@end